package com.dc.docs._888_面试.concurrent._6_queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * Description: 一个不存储元素的阻塞队列
 * @author: gdc
 * @date: 2021/6/16
 * @version 1.0
 */
public class SynchronousQueueDemo {

    public static void main(String[] args){
        BlockingQueue<String> queue = new SynchronousQueue<>();

        // 添加队列元素，当队列包含元素，线程会被阻塞掉，直到元素为空
        new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + ", put 1");
                queue.put("1");

                System.out.println(Thread.currentThread().getName() + ", put 2");
                queue.put("2");

                System.out.println(Thread.currentThread().getName() + ", put 3");
                queue.put("3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "AA").start();

        // 获取队列元素，当队列元素为空时，会被阻塞掉
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName() + ", take: " + queue.take());

                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName() + ", take: " + queue.take());

                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName() + ", take: " + queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "BB").start();
    }
}
